import {
	sendCodeAPI,
	userRegisterAPI,
	userLoginAPI,
	getUserInfoAPI,
	userLogoutAPI,
} from "@/api";

import { getToken, setToken, removeToken } from "@/utils/token";

const state = {
	code: "",
	token: getToken(),
	userInfo: {},
};
const mutations = {
	SENDCode(state, data) {
		state.code = data;
	},
	USERLOGIN(state, token) {
		state.token = token;
	},
	USERINFO(state, userInfo) {
		state.userInfo = userInfo;
	},
	USERLOGOUT(state) {
		state.code = "";
		state.userInfo = {};
		state.token = "";
		removeToken();
	},
};
const actions = {
	// 获取验证码
	async sendCode({ commit }, phone) {
		const res = await sendCodeAPI(phone);
		if (res.code === 200) {
			commit("SENDCode", res.data);
			return "ok";
		} else {
			return Promise.reject(new Error("fail"));
		}
	},

	// 用户注册
	async userRegister(context, { phone, password, code }) {
		const res = await userRegisterAPI({ phone, password, code });
		if (res.code === 200) {
			return "ok";
		} else {
			return Promise.reject(new Error("fail"));
		}
	},

	// 用户登录 -- 单击登录按钮
	async userLogin({ commit }, { phone, password }) {
		const res = await userLoginAPI({ phone, password });

		if (res.code === 200) {
			commit("USERLOGIN", res.data.token);
			setToken(res.data.token); // 将token存储到本地仓库
		} else {
			return Promise.reject(new Error("登录失败", res.message));
		}
	},

	// 获取用户信息
	async getUserInfo({ commit }) {
		const res = await getUserInfoAPI();
		if (res.code === 200) {
			commit("USERINFO", res.data);
		} else {
			return Promise.reject(new Error(res.message));
		}
	},

	// 退出登录
	async userLogout({ commit }) {
		const res = await userLogoutAPI();
		if (res.code === 200) {
			commit("USERLOGOUT");
		} else {
			return Promise.reject(new Error("logout fail"));
		}
	},
};
const getters = {};

export default {
	namespaced: true,
	state,
	mutations,
	actions,
	getters,
};
